<?php

namespace App\Actions;


use App\Dao\AnchorDao;
use App\Dao\ClosenessDao;
use App\Dao\CommonSettingDao;
use App\Dao\UserDao;
use App\Model\User;
use App\Services\PushMessageService;
use App\Utils\FunUtil;
use App\Utils\MongoDBClient;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class MessageAction
{
    public function __construct()
    {
        /*parent::__construct();*/
    }


    /**
     * 组装搭讪数据结构
     * @param $fromUid
     * @param $toUid
     * @param $content
     * @param $content_type
     * @param $chat_type
     * @return bool
     */
    public function sendAccostMsg($fromUid, $toUid, $content, $content_type = 1, $chat_type = 5, $audio_time = 0, $img_w = 0, $img_h = 0, $sync_sender = 1)
    {
        try {
            // $userModel = new UserModel();
            $senderUser = User::findUserInfoById($fromUid);
            if ($senderUser['sex'] == 1) {
                $uid = $fromUid;
                $anchor_id = $toUid;
            } else {
                $uid = $toUid;
                $anchor_id = $fromUid;
            }
            $time = getMillisecond();

            $sender = $this->formatUserInfo($senderUser);

            $from = $sender["from"];
            $version_code = $sender["version_code"];
            $channel = $sender["channel"];

            if (isset($sender['from'])) unset($sender['from']);
            if (isset($sender['version_code'])) unset($sender['version_code']);
            if (isset($sender['channel'])) unset($sender['channel']);

            $msgData['closeness'] = ClosenessDao::read($uid, $anchor_id);
            $msgData['uid'] = (int)$fromUid;    //发送方
            $msgData['receive_uid'] = (int)$toUid;   //接收方
            $msgData['content'] = $content;
            $msgData['from'] = (int)$from;
            $msgData['version_code'] = (int)$version_code;
            $msgData['ctime'] = $time;
            $msgData['audio_time'] = $audio_time;
            $msgData['w'] = $img_w;
            $msgData['h'] = $img_h;
            $msgData['chat_type'] = $chat_type;
            $msgData['message_price'] = $chat_type == 5 ? '0.40' : 0;
            $msgData['message_id'] = md5(getMillisecond() . rand(1000, 9999));
            $msgData['sync_sender'] = $sync_sender;
            $msgData['channel_number'] = $channel;  //渠道号
            $msgData['content_type'] = $content_type; //1文本消息，2语音消息，3图片消息
            $msgData['msg_type'] = 2;
            $msgData['is_red'] = $this->getReadMsg(intval($fromUid), intval($toUid));
            // 新人标识
            $msgData['to_is_new_user'] = 0;
            $msgData['user_info'] = $sender;
            // $receiver = $userModel->find("`id`, `nickname`, `head_image`,`online`", "id = ?", [$toUid]);
            $receiver = User::query()->where('id', $toUid)->select(['id', 'nickname', 'head_image', 'online', 'register_time'])->first();
            $receiver = modelToArray($receiver);
            $msgData['receiver'] = $receiver;

            $msgData['to_is_new_user'] = ($receiver['register_time'] + 7 * 86400 >= time()) ? 1 : 0;
            $msgData['is_new_user'] = ($senderUser["register_time"] + 7 * 86400 >= time()) ? 1 : 0;

            $msgData['content'] = htmlspecialchars($msgData['content']);

            $msg[0] = $msgData;
            $message = json_encode(['event' => 'user_conn', 'msg' => $msg, 'desc' => '获取成功'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

            // return (new WyyClient())->putCustomMsgQueue($fromUid, $toUid, $message);
            return PushMessageService::putYunXinCustomMsgQueue($fromUid, $toUid, $message);
        } catch (\Throwable $e) {
            logInfo("send_msg_queue", [
                "uid" => $fromUid,
                "message" => $e->getMessage(),
                "file" => $e->getFile(),
                "line" => $e->getLine(),
            ]);
            return false;
        }
    }


    /**
     * 根据用户性别，发消息个数确定发文本消息还是语音消息
     * @param $userInfo
     * @param $option
     * @return int
     */
    public function getContentType($userInfo, $option)
    {
        $content_type = $option['content_type'];
        $type = $option['stage_type'];
        $commonConfig = $this->_commonConfig;
        if ($userInfo['sex'] == 2) {
            //女性用户全部是文字消息
            $content_type = 1;
        } else {
            //男性用户
            if ($type == 8) {
                return 1;
            }
            //必须控制机器人语音出现的次数：每次打开应用、每个场景最多3条
            //男性用户收到的前5条机器人消息中，最少有一条语音消息；
            //判断前五条是否有语音

            $key = "robot_msg_times_" . $userInfo['id'];
            $robot_msg_times = Mem::get($key); //发送消息的次数

            if ($robot_msg_times >= $commonConfig['audio_times_pre']) {
                $key3 = "robot_pre_content_type_2_" . $userInfo['id'];
                $pre_audio_msg_times = Mem::get($key3);   //前4次发送语音消息的次数

                if ($pre_audio_msg_times <= 0) {
                    $content_type = 2;
                }

            }
            //机器人语音出现次数
            if ($content_type == 2) {
                $audio_times = $this->getAudioTimesByUidAndType($userInfo['id'], $type);

                if ($audio_times >= $commonConfig['audio_times']) {
                    //超过了每个场景出现的最大次数,则获取文本消息
                    $content_type = 1;
                }
            }
        }
        if ($option['stage_type'] == 6) {   //场景为6时（给vip用户发送引导），使用文本消息
            $content_type = 1;
        }
        if ($_REQUEST['from'] == -1) {
            //ios通知，不获取语音消息
            $content_type = 1;
        }
        return $content_type;
    }

    /**
     * 获取用户和消息内容
     * 1,获取用户消息（指定用户或者随机用户）
     * 2，根据语音消息或者文本消息或者对应的消息内容
     * @param $userInfo
     * @param $option
     * $option['user_id']=$user_id;
     * $option['stage_type']=$type;
     * $option['content_type']=$content_type;
     * $option['source_id']=$source_id;
     * @return array
     */
    public function getMessage($userInfo, $option)
    {
        $data = array();
        return $data;
    }

    /**
     * 优化脚本和托管未读消息的上限条数
     * @param $uid
     * @param $status
     */
    public function setMessageUidStatus($uid, $status = 1)
    {
        $messageUid = (array)Mem::get("message_uid_status");
        if ($status == 1) {
            if (!isset($messageUid) || !in_array($uid, $messageUid)) {
                $messageUid[] = $uid;
            }
        } else {
            if (isset($messageUid) && !empty($messageUid)) {
                if (isset($messageUid[0])) unset($messageUid[0]);
                if (isset(array_flip($messageUid)[$uid])) unset($messageUid[array_flip($messageUid)[$uid]]);
            }
        }
        Mem::set("message_uid_status", $messageUid);
    }

    /**
     * 随机获取一个用户id
     * @param $userInfo
     * @return int
     */
    public function getRandUid($userInfo)
    {
        $userModel = new UserModel();
        $uids = $userModel->findOnlineShowUserUids($userInfo['sex']);
        //过滤用户id
        $uids = $this->filterRandUids($uids, $userInfo);
        //把套路机器人的id过滤
        $filterUids = $this->filterUids();
        $uids = array_diff($uids, $filterUids);

        foreach ($uids as $k => $v) {
            if ($v == $userInfo['id']) {
                unset($uids[$k]);
            }
        }
        shuffle($uids);
        $uid = (int)$uids[0];
        return $uid;
    }

    public function filterRandUids($uids, $userInfo)
    {
        $rate = 20;   //使用主播用户发消息的概率
        if ($userInfo['sex'] == 1) {
            $online_anchors = Mem::get('online_anchor_uids');
            if (!empty($online_anchors) && mt_rand(0, 10000) <= $rate * 100) {
                $tmp = [];
                foreach ($online_anchors as $v) {
                    $tmp[] = $v;
                }
                $uids = $tmp;
                Tool::log('robot_uids.txt', $uids, '使用在线主播');
            }
        }
        //Tool::log('filter_rand_uids.txt',$uids,'使用在线主播');
        return $uids;
    }

    /**
     * 获取用户消息
     * 1，根据消息类型获取
     * 2，根据性别获取
     * 3，根据时间获取
     * 4，根据消息场景获取
     * 5，根据语音消息声源id获取
     * 6，根据语音消息内容获取
     *
     * @param $userInfo
     * @param $tarUserInfo
     * @param $option
     * $option['user_id']=$user_id;
     * $option['stage_type']=$type;
     * $option['content_type']=$content_type;
     * $option['source_id']=$source_id;
     * @return array
     */
    public function getMessageData($userInfo, $tarUserInfo, $option)
    {
        $tarSex = $userInfo['sex'] == 2 ? 1 : 2;
        $egMsg = $this->getEgMsgDb();   //所有消息文案
        if (!empty($egMsg)) {
            //判断是否场景7
            if ($option['user_id'] == -1 && /*$userInfo['vip'] == 0 &&*/ $_REQUEST['from'] != -1 && $option['content_type'] == 1 && $option['novip_guide'] == 1) {
                $guide_flag = $this->checkNovipGuide($userInfo);
                if ($guide_flag) {
                    $option['stage_type'] = 7;
                }
            }

            $filter1 = array();
            foreach ($egMsg as $item => $value) {
                //根据消息类型获取,根据性别获取,根据消息场景获取
                if ($value['msg_type'] == $option['content_type'] && $value['sex'] == $tarSex && $value['type'] == $option['stage_type']) {
                    if ($value['limit_hour'] == 1) {
                        $h = date("H");
                        if ($value['s_hour'] >= $h && $value['e_hour'] <= $h) {
                            $filter1[] = $value;
                        }
                    } else {
                        $filter1[] = $value;
                    }
                }
            }
            $analysis = $this->formatHistoryCache($userInfo);
            $historyContentType = (array)$analysis[$option['content_type']];
            if ($option['content_type'] == 1) {
                //文本消息，获取确定的一条文本消息
                $formatArr = array();
                if (!empty($filter1)) {
                    foreach ($filter1 as $k => $v) {
                        $formatArr[$v['id']] = $v;
                    }
                }
                //在场景为1的情况下，概率获取联系方式消息-start
                if ($option['stage_type'] == 1) {
                    $contact_flag = $this->getContactFlag($userInfo, $tarUserInfo, $option);    //获取是否使用联系方式消息
                    $contactData1 = $contactData2 = array();
                    if (!empty($formatArr)) {
                        foreach ($formatArr as $k1 => $v1) {
                            if ($v1['contact_type'] != 0) {
                                $contactData1[$v1['id']] = $v1;
                            } else {
                                $contactData2[$v1['id']] = $v1;
                            }
                        }
                    }
                    if ($contact_flag == 1) {
                        $formatArr = $contactData1;
                        $filter2_tmp = array_diff_key($formatArr, $historyContentType);    //剔除历史记录中存在的记录
                        if (empty($filter2_tmp)) {
                            $formatArr = $contactData2;
                            $contact_flag = 0;
                        }
                    } else {
                        $formatArr = $contactData2;
                    }
                }
                //在场景为1的情况下，概率获取联系方式消息-end

                //在场景为6的情况下，概率获取推广消息-start
                if ($option['stage_type'] == 6) {
                    $mo_arr1 = $mo_arr2 = array();
                    $mo_flag = 0;
                    $mo_rate = 50;
                    if (mt_rand(0, 100) <= $mo_rate) {
                        $mo_flag = 1;
                    }
                    if (!empty($formatArr)) {
                        foreach ($formatArr as $k1 => $v1) {
                            if (preg_match("/\[\[.+\]\]/", $v1['content'])) {
                                //匹配到是模版消息
                                $mo_arr1[$k1] = $v1;
                            } else {
                                $mo_arr2[$k1] = $v1;
                            }
                        }
                    }
                    //查看客户端是否请求了推广接口(/app/mailbox/spread_info.php)
                    $spread = Mem::get("spread_app_" . $userInfo['id']);
                    if (!empty($spread) && !empty($mo_arr1) && $mo_flag == 1 && $option['novip_guide'] != 0) {
                        foreach ($mo_arr1 as $k2 => $v2) {
                            if (preg_match("/\[\[{$spread['app_name']}\]\]/", $v2['content'])) {
                                //匹配到是模版消息
                                $tt = str_replace("[[", "", $v2['content']);
                                $tt1 = str_replace("]]", "", $tt);
                                $app_url = $spread['app_url'];
                                if ($_REQUEST['from'] == 2) {
                                    $app_url = $spread['ios_url'];
                                }
                                $v2['content'] = $tt1 . "<a href='{$app_url}'>{$app_url}</a>";
                                $mo_arr3[$k2] = $v2;
                            }
                        }
                        $formatArr = $mo_arr3;
                        if (empty($formatArr)) {
                            $formatArr = $mo_arr2;
                        }
                    } else {
                        $formatArr = $mo_arr2;
                    }
                    /* echo '<pre>';var_dump($spread,$spread['app_name'],$mo_arr3);
                     die;*/
                }
                //在场景为6的情况下，概率获取推广消息-end

                //场景7 start
                if ($option['stage_type'] == 7) {
                    if (!empty($formatArr)) {
                        $mo_msg = array();
                        $novipSpreadApp = $this->getNovipSpreadApp();
                        foreach ($formatArr as $_k => $_v) {
                            if (preg_match("/\[\[{$novipSpreadApp['app_name']}\]\]/", $_v['content'])) {
                                $_content = str_replace(array("[[", "]]"), "", $_v['content']);
                                $app_url = $novipSpreadApp['app_url'];
                                if ($_REQUEST['from'] == 2) {
                                    $app_url = $novipSpreadApp['ios_url'];
                                }
                                $_v['content'] = $_content . "<a href='{$app_url}'>{$app_url}</a>";
                                $_v['type'] = 7;
                                $mo_msg[$_k] = $_v;
                            }
                        }
                        $formatArr = $mo_msg;
                    }
                }
                //场景7 end

                //场景8  start
                if ($option['stage_type'] == 8) {
                    // VIP用户才会有的，这里排重不用原有的缓存，而是根据客户端传来的yids
                    /*if($userInfo['vip'] == 1){*/
                    if (!empty($formatArr)) {
                        //$option['yids'] = '';  //如果需要排重，请注释此行代码
                        if (!empty($option['yids'])) {
                            $yids = explode(",", $option['yids']);
                            foreach ($formatArr as $k => $v) {
                                if (in_array($v['id'], $yids)) {
                                    unset($formatArr[$k]);
                                }
                            }
                        }
                    }
                    /*}else{
                        $formatArr = array();
                    }  */
                }
                //场景8  end

                //获取随机一条未使用的文本id
                if ($option['stage_type'] != 8) {
                    $filter2 = array_diff_key($formatArr, $historyContentType);    //剔除历史记录中存在的记录
                    //echo '<pre>';var_dump($filter2);die;
                    if (empty($filter2)) {
                        //如果改该类型的记录已经用光，就清除历史记录缓存
                        $this->delHistoryCache($userInfo);
                        $filter2 = $formatArr;
                    }
                } else {
                    $filter2 = $formatArr;
                }

                $msgRow = array();
                if (!empty($filter2)) {
                    $index = array_rand($filter2);
                    //已确定的文本消息
                    $msgRow = $formatArr[$index];
                }


            } elseif ($option['content_type'] == 2) {
                //语音消息，1，根据语音消息声源id获取 2，根据语音消息内容获取
                $formatArr = array();
                if (!empty($filter1)) {
                    foreach ($filter1 as $k => $v) {
                        $formatArr[$v['source_id']][$v['content_code']][] = $v;
                    }
                }
                $source_id = $option['source_id'];
                //客户端传不存在的声源id，就获取一个随机声源id
                $historyContentType = (array)$historyContentType[$option['stage_type']];
                if (empty($formatArr[$source_id])) {
                    ///////////////待从历史记录中剔除已经用过的声源id(source_id)/////////////////////////
                    $diff1 = $formatArr;
                    if (!empty($historyContentType)) {
                        $diff1 = array_diff_key($formatArr, $historyContentType);
                        if (empty($diff1)) {
                            $this->delHistoryCache($userInfo);
                            $diff1 = $formatArr;
                        }
                    }
                    $source_id = array_rand($diff1);
                }
                $formatArr2 = $formatArr[$source_id];   //已确定声源，语音消息内容待确定
                ///////////////待从历史记录中剔除已经用过的消息内容(content_code)/////////////////////////
                $diff2 = $formatArr2;
                if (!empty($historyContentType[$source_id])) {
                    $diff2 = array_diff_key($formatArr2, $historyContentType[$source_id]);
                }

                //    var_dump($diff2);die;
                if (empty($diff2)) {
                    $this->delHistoryCache($userInfo);
                    $diff2 = $formatArr2;
                }
                $code_index = array_rand($diff2);
                $code_index_son = array_rand($formatArr2[$code_index]);

                //已确定的语音消息
                $msgRow = $formatArr2[$code_index][$code_index_son];
            }


            //将已经获取的消息文案加入到历史缓存中
            $option['stage_type'] != 8 && $this->addHistoryCache($userInfo, $msgRow);
            return $msgRow;
        } else {
            return array();
        }
    }

    /**
     * 从数据库获取机器人的消息文案，把文案分成10组缓存
     */
    public function getEgMsgDb()
    {
        $flag = false;
        $indexCount = Mem::get('api_message_db_new_index_count');
        if ($indexCount === false) {
            $flag = true;
        } else {
            for ($i = 0, $len = intval($indexCount); $i < $len; $i++) {
                $item = Mem::get("api_message_db_new_" . $i);
                if ($item === false) {
                    $flag = true;
                    break;
                } else {
                    $sonData1[$i] = $item;
                }
            }

        }
        if ($flag) {
            $page = 10;
            $robotModel = new RobotmessageModel();
            $data = $robotModel->getRobotMsgBySexV2();
            if (!empty($data)) {
                foreach ($data as $k => $v) {
                    $mi = $v['id'] % $page;
                    $sonData[$mi][$k] = $v;
                }
            }
            if (!empty($sonData)) {
                foreach ($sonData as $item => $value) {
                    Mem::set("api_message_db_new_" . $item, $value, 300);
                }
                Mem::set("api_message_db_new_index_count", count($sonData), 300);     //所有消息分拆的个数
            }
        } else {
            $data = array();
            if (!empty($sonData1)) {
                foreach ($sonData1 as $v1) {
                    foreach ($v1 as $k2 => $v2) {
                        $data[$k2] = $v2;
                    }
                }
            }

            ksort($data);
        }
        return $data;
    }

    /**
     * 将获取到的消息信息加入到历史缓存中
     * @param $data
     */
    public function addHistoryCache($userInfo, $data)
    {
        $history['i'] = $data['id'];
        $history['c'] = $data['msg_type'];
        $history['t'] = $data['type'];
        $history['s'] = $data['source_id'];
        $history['cc'] = $data['content_code'];

        $row = "{$history['i']}_{$history['c']}_{$history['t']}_{$history['s']}_{$history['cc']}";
        $cache = Mem::get("api_user_msg_history_" . $userInfo['id']);
        if (empty($cache)) {
            $cache = '';
        }
        $cache .= "," . $row;
        $cache = trim($cache, ',');
        Mem::set("api_user_msg_history_" . $userInfo['id'], $cache, 3600);
    }

    /**
     * 获取用户的收到的消息历史记录
     * @param $userInfo
     * @return array
     */
    public function analysisHistoryCache($userInfo)
    {
        $cache = Mem::get("api_user_msg_history_" . $userInfo['id']);
        $data = array();
        if (!empty($cache)) {
            $analysis = explode(',', $cache);
            if (!empty($analysis)) {
                foreach ($analysis as $k => $v) {
                    $row = explode('_', $v);
                    $rowArr['id'] = $row[0];
                    $rowArr['content_type'] = $row[1];
                    $rowArr['type'] = $row[2];
                    $rowArr['source_id'] = $row[3];
                    $rowArr['content_code'] = $row[4];
                    $data[] = $rowArr;
                }
            }
        }
        return $data;
    }

    public function delHistoryCache($userInfo)
    {
        Mem::delete("api_user_msg_history_" . $userInfo['id']);
    }

    /**
     * 格式化获取的用户接收过得历史消息缓存
     * @param $userInfo
     * @return array
     */
    public function formatHistoryCache($userInfo)
    {
        $data = $this->analysisHistoryCache($userInfo);
        $result = array();
        if (empty($data)) return $result;
        foreach ($data as $k1 => $v1) {
            if ($v1['content_type'] == 1) {
                $result[$v1['content_type']][$v1['id']] = $v1;
            } elseif ($v1['content_type'] == 2) {
                $result[$v1['content_type']][$v1['type']][$v1['source_id']][$v1['content_code']][] = $v1;
            }
        }
        return $result;
    }

    /**
     * 获取语音文件的播放时长
     * @param $message
     * @return float
     */
    public function getAudioTime($message)
    {
        if (!class_exists('getID3')) {
            require ROOT_PATH . "lib/tool/getID3/getid3/getid3.php";
        }
        if (!preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is', $message)) {
            $tmp = str_replace(IMAGE_HOST, "", $message);
            $fileUrl = ROOT_PATH . "public/" . $tmp;
        } else {
            $fileUrl = $message;
        }

        $getID3 = new getID3();    //实例化类
        $ThisFileInfo = $getID3->analyze($fileUrl);    //分析文件
        Tool::log('push_message.txt', 'data:' . json_encode($ThisFileInfo), '获取mp3的长度信息 ');
        $time = $ThisFileInfo['playtime_seconds'];        //获取mp3的长度信息
        unset($getID3);
        return round($time);
    }

    public function formatUserInfo($userInfo)
    {
        if (empty($userInfo)) {
            return array();
        }
        $data['id'] = $userInfo['id'];
        $data['nickname'] = $userInfo['nickname'];
        $data['head_image'] = $userInfo['head_image'];
        // $data['vip'] = $userInfo['noble'];
        $data['noble'] = intval($userInfo['noble']);
        // $data['super_noble'] = intval($userInfo['super_noble']);
        $data['sex'] = $userInfo['sex'];
        // $data['user_type'] = $userInfo['user_type'];
        $data['from'] = $userInfo['from'];
        $data['version_code'] = $userInfo['version_code'];
        $data['channel'] = $userInfo['channel'];
        // $data['last_login_ip'] = $userInfo['last_login_ip'];

        // $data['enable_call'] = 1;
        $data['video_price'] = 0;
        $data['audio_price'] = 0;
        // $data['video_url'] = '';
        if ($userInfo['sex'] == 2) {
            $anchor = AnchorDao::getInstance()->findAnchorInfoCache($userInfo['id']);
            if (!empty($anchor) && $anchor['status'] == 0) {
                $data['call_show_type'] = $anchor['call_show_type'];
                $data['call_show'] = $anchor['call_show'];

                // $data['enable_call'] = 1;
                $data['video_price'] = $anchor['video_price'];
                $data['audio_price'] = $anchor['audio_price'];
            }
        }
        $data['online'] = $userInfo['online'];
        $data['gift_count'] = $userInfo['gift_count'];
        // $data['level'] = $userInfo['level'];
        $data['height'] = $userInfo['height'] . 'cm';
        $data['age'] = $userInfo['age'] . '岁';
        $data['city'] = $userInfo['city'];
        $data['province'] = $userInfo['province'] ?: '保密';
        $data['weight'] = $userInfo['ext']->weight ?? "60kg";

        return $data;
    }

    public function formatUserInfo1($userInfo)
    {
        if (empty($userInfo)) {
            return array();
        }
        $data['id'] = $userInfo['id'];
        $data['nickname'] = $userInfo['nickname'];
        $data['head_image'] = $userInfo['head_image'];
        // $data['vip'] = $userInfo['noble'];
        $data['noble'] = intval($userInfo['noble']);
        // $data['super_noble'] = intval($userInfo['super_noble']);
        $data['sex'] = $userInfo['sex'];
        // $data['user_type'] = $userInfo['user_type'];
        $data['from'] = $userInfo['from'];
        $data['version_code'] = $userInfo['version_code'];
        $data['channel'] = $userInfo['channel'];
        // $data['last_login_ip'] = $userInfo['last_login_ip'];

        // $data['enable_call'] = 1;
        $data['video_price'] = 0;
        $data['audio_price'] = 0;
        // $data['video_url'] = '';
        if ($userInfo['sex'] == 2) {
            $anchorModel = new AnchorModel();
            $anchor = $anchorModel->findAnchorInfoCache($userInfo['id']);
            if (!empty($anchor) && $anchor['status'] == 0) {
                // $data['enable_call'] = 1;
                $data['video_price'] = $anchor['video_price'];
                $data['audio_price'] = $anchor['audio_price'];
            }
        }
        $data['online'] = $userInfo['online'];
        $data['gift_count'] = $userInfo['gift_count'];
        // $data['level'] = $userInfo['level'];
        $data['height'] = $userInfo['height'] . 'cm';
        $data['age'] = $userInfo['age'] . '岁';
        $data['city'] = $userInfo['ext']->constellation ?? "保密";
        $data['province'] = $userInfo['province'] ?: '保密';
        $data['weight'] = isset($userInfo['ext']->weight) ? $userInfo['ext']->weight : "60kg";
        return $data;
    }

    /**
     * 删除各场景中用户的语音使用次数缓存
     * @param $uid
     * @param $type
     * @return int
     */
    public function getAudioTimesByUidAndType($uid, $type)
    {
        $flag = Mem::get("robot_audio_times_flag_" . $uid);
        if ($flag === false) {
            Mem::delete("robot_audio_times_" . $uid . "_1");
            Mem::delete("robot_audio_times_" . $uid . "_2");
            Mem::delete("robot_audio_times_" . $uid . "_3");
            Mem::delete("robot_audio_times_" . $uid . "_4");
            Mem::delete("robot_audio_times_" . $uid . "_5");
            Mem::delete("robot_audio_times_" . $uid . "_6");
        }
        $times = intval(Mem::get("robot_audio_times_" . $uid . "_" . $type));
        return $times;
    }

    /**
     * 设置语音语音出现的次数
     * @param $userInfo
     * @param $message
     */
    public function setUserRobotAudioTimes($userInfo, $message)
    {
        Mem::add("robot_audio_times_flag_" . $userInfo['id'], 1, 43200);
        //发消息次数
        $key = "robot_msg_times_" . $userInfo['id'];
        if (!Mem::add($key, 1, 43200)) {
            Mem::increment($key, 1);
        }
        //语音消息时添加语音消息的发送次数
        if (!empty($message) && $message['content_type'] == 2) {
            $key2 = "robot_audio_times_" . $userInfo['id'] . "_" . $message['type'];
            if (!Mem::add($key2, 1, 43200)) {
                Mem::increment($key2, 1);
            }
        }
        if ($message['content_type'] == 2) {
            $key3 = "robot_pre_content_type_2_" . $userInfo['id'];
            if (!Mem::add($key3, 1, 43200)) {
                Mem::increment($key3, 1);
            }
        }
    }

    /**
     * 插入用户聊天记录
     * @param $data
     * @param array $message
     * @return bool
     */
    public function insertUserChat($data, $message = [])
    {
        $insertData = [];
        //使用毫秒级
        $micotime = microtime(true);
        $suggestion = isset($data['suggestion']) ? intval($data['suggestion']) : 0;
        $label = isset($data['label']) && is_numeric($data['label']) ? intval($data['label']) : $data['label'];
        $guild_num = $data['guild_num'] ?? '';
        if ($data['msg_type'] == 2) {
            //用户发消息给机器人或真实用户
            $tarUserInfo = UserDao::getInstance()->findUserInfoCache($data['user_id']);
            $userInfo = UserDao::getInstance()->findUserInfoCache($data['uid']);

            $char_type = isset($data['type']) ? intval($data['type']) : 4;
            $insertData = array();
            $insertData['uid'] = (int)$data['uid'];   //发送方
            $insertData['receive_uid'] = (int)$data['user_id'];   //接收方
            $insertData['content'] = $data['content'];
            $insertData['ip'] = FunUtil::getClientIp();
            $insertData['from'] = (int)$data['from'];
            $insertData['version_code'] = (int)$data['version_code'];
            $insertData['ctime'] = $micotime;
            $service_id = 0;

            $insertData['audio_time'] = isset($_REQUEST['audio_time']) ? (int)$_REQUEST['audio_time'] : 0;  //语音时长
            $insertData['service_id'] = $service_id;
            $insertData['chat_type'] = $char_type;     //chat_type 1用户对机器人说，2客服对用户说(红娘对用户说),3机器人对用户说,4用户对用户说,5用户对红娘说,6客服对用户说
            $insertData['suggestion'] = $suggestion;
            $insertData['label'] = $label;
            $insertData['guild_num'] = $guild_num;
            $insertData['gid'] = 0;   //套路消息id
            $insertData['m_id'] = 0;

            $insertData['message_id'] = $data['message_id'];  //消息id
            $insertData['message_price'] = $data['message_price'];    //女用户收益

            // 判断是否开启回复消息获得收益
            if (CommonSettingDao::getValue('REPLY_INCOME') == 1 && $data['message_price'] != 0) {
                $insertData['is_settle'] = $data['sync_sender'] == 2 ? 2 : 0;    // 是否结算 0待结算 1已结算 2已过期
            } else {
                $insertData['is_settle'] = 1;    // 是否结算 0待结算 1已结算 2已过期
            }
            $insertData['text_price'] = $userInfo['sex'] == 1 ? ($char_type == 5 ? 1 : (($char_type == 3 && $data['sync_sender'] != 2) ? 0.25 : (intval($tarUserInfo['text_price'] ?? 0)))) : 0;    // 目标用户聊天价格（金币）

            $insertData['channel_number'] = $_REQUEST['channel'] ?? $data['channel_number'];  //渠道号
            $insertData['content_type'] = !empty($data['content_type']) ? (int)$data['content_type'] : 1; //1文本消息，2语音消息，3图片消息
            $insertData['charge_photo'] = isset($data['charge_photo']) ? intval($data['charge_photo']) : 0;//是否为收费图片
            $insertData['sex'] = (int)$userInfo['sex'];   //发送方性别
            $insertData['receive_sex'] = (int)$tarUserInfo['sex'];    //接收方性别
            $insertData['user_type'] = (int)$userInfo['user_type'];   //发送方用户类型
            $insertData['receive_user_type'] = (int)$tarUserInfo['user_type'];    //接收方用户类型
            $insertData['vip'] = (int)$userInfo['vip'];   //发送方vip
            $insertData['redpacket'] = 0;
            $insertData['ch_id'] = isset($data['chat_hosting_anchor_id']) ? (int)$data['chat_hosting_anchor_id'] : 0; // 聊天主播id 只用于聊天主播功能
            $insertData['taskId'] = empty($data['taskId']) ? '' : $data['taskId'];
            if ($char_type != 4) {
                $insertData['review_suggestion'] = 1;
                $insertData['review_time'] = time();
            }
            if ($data['content_type'] == 2 && isset($data['audio_text'])) { // 语音消息，附带语音识别的文本
                $insertData['audio_text'] = $data['audio_text'];
            }
        } else {
            //机器人发消息给用户
            if ($message['result'] == 1 && !empty($message['msg'])) {
                $msg = $message['msg'];
                $insertData = array();
                $insertData['uid'] = (int)$msg['user_info']['id'];    //发送方
                $insertData['receive_uid'] = (int)$data['uid'];   //接收方
                $insertData['content'] = $msg['message'];
                $insertData['ip'] = FunUtil::getClientIp();
                $insertData['from'] = (int)$data['from'];
                $insertData['version_code'] = (int)$data['version_code'];
                $insertData['ctime'] = $micotime;
                $insertData['service_id'] = 0;
                $insertData['chat_type'] = 3;     //chat_type 1用户对机器人说，2客服对用户说(红娘对用户说),3机器人对用户说,4用户对用户说,5用户对红娘说,6客服对用户说
                $insertData['suggestion'] = $suggestion;
                $insertData['label'] = $label;
                $insertData['guild_num'] = $guild_num;
                $insertData['gid'] = (int)$msg['gid'];
                $insertData['m_id'] = (int)$msg['m_id'];
                $insertData['channel_number'] = isset($_REQUEST['channel']) ? $_REQUEST['channel'] : '';  //渠道号
                $insertData['content_type'] = !empty($msg['content_type']) ? (int)$msg['content_type'] : 1; //1文本消息，2语音消息，3图片消息

                $tarUserInfo = UserDao::getInstance()->findUserInfoCache($insertData['receive_uid']);
                $userInfo = UserDao::getInstance()->findUserInfoCache($insertData['uid']);
                $insertData['sex'] = (int)$userInfo['sex'];   //发送方性别
                $insertData['receive_sex'] = (int)$tarUserInfo['sex'];    //接收方性别
                $insertData['user_type'] = (int)$userInfo['user_type'];   //发送方用户类型
                $insertData['receive_user_type'] = (int)$tarUserInfo['user_type'];    //接收方用户类型
                $insertData['vip'] = (int)$userInfo['vip'];   //发送方vip
                $insertData['audio_time'] = isset($_REQUEST['audio_time']) ? (int)$_REQUEST['audio_time'] : 0;  //语音时长
                $insertData['taskId'] = empty($data['taskId']) ? '' : $data['taskId'];
                $insertData['review_suggestion'] = 1;
                $insertData['review_time'] = time();
            }
        }
        if (!empty($insertData)) {
            //插入到mongo
//            $insertData['look']=0;  //是否已读
//            $insertData['date']=date("Y-m-d");
            $mongo = MongoDBClient::getInstance();
            $mongo->insert('tb_user_chat_v2', $insertData);
            return true;
        }
        return false;
    }


    /**
     * 女用户回复消息，获取收益
     * @param $anchor_id
     * @param $user_id
     * @param $times
     * @return bool
     */
    public function messageSettle($anchor_id, $user_id, $times = 0)
    {
        $mongo = new MonDB();

        // 获取在这之前的未处理消息
        // 主播发送的私信
        $where = [
            'uid' => intval($user_id),
            'receive_uid' => intval($anchor_id),
            'is_settle' => ['$in' => [0, 3]],
            'chat_type' => ['$in' => [3, 4, 5]],
            'content_type' => ['$in' => [1, 2, 3]],
            'message_id' => ['$nin' => [null, '']]
        ];
        if ($times) {
            $where['ctime'] = ['$lt' => $times];
        }

        $options = array(
            'projection' => array('_id' => 0, 'uid' => 1, 'receive_uid' => 1, 'ctime' => 1, 'message_id' => 1, 'text_price' => 1, 'chat_type' => 1, 'content_type' => 1, 'is_settle' => 1, 'message_price' => 1),
            'skip' => 0,
            'sort' => array('ctime' => -1)
        );
        $result = $mongo->find($where, $options, MON_USER_CHAT);

        logInfo("message_settle", $result);

        if (!empty($result)) {
            $userModel = new UserModel();
            $userInfo = $userModel->find('id,gift_count,package,version_code,channel,`from`,`online`', 'id=?', [$user_id]);
            $anchorInfo = $userModel->find('id,integrate_usable_count,version_code,`from`,package,version_code,channel,guild_num', 'id=?', [$anchor_id]);


            $messageIds = [];        // 已结算消息id
            $overMessageIds = [];        // 已过期消息id
            $incomeArr = [];

            $msgId = [];

            $anchor_income = 0;    // 主播收入
            $user_back = 0;        // 用户退回金币

            $expend = 0;    // 男用户消耗金币
            $time = time();

            $allMessageIds = implode("','", array_column($result, 'message_id'));

            $goldFrom = $userModel->findAll("id,extent,gold_from", "extend in ('$allMessageIds')", [], '', '', "tb_income_expense");
            if (!empty($goldFrom)) {
                $goldFrom = array_column($goldFrom, 'gold_from', 'extent');
            }

            foreach ($result as $item) {
                // todo 测试过期时间为2分钟，正式上线为8小时
                // if(intval($item['ctime']) >= time()-8*3600 ){
                if (intval($item['ctime']) >= $time - 60) {
                    // 未过期消息，给女用户结算

                    $profit = $item['message_price'];

                    $anchor_income = bcadd($anchor_income, $profit, 2);

                    $income = [
                        'uid' => $anchor_id,
                        'user_id' => $user_id,
                        'type' => 1,
                        'sub_type' => 7,
                        'amount_type' => 2,
                        'amount' => $profit,
                        'account' => bcadd($anchorInfo['integrate_usable_count'], $anchor_income, 2),
                        'ext' => json_encode(["p" => $userInfo['package'], 'v' => $userInfo['version_code'], 'c' => $userInfo['channel']]),
                        'rate' => 40,
                        'extend' => $item['message_id'],
                        'from' => $anchorInfo['from'],
                        'version_code' => $anchorInfo['version_code'],
                        'channel' => $anchorInfo['channel'],
                        'package' => $anchorInfo['package'],
                        'guild_num' => $item['chat_type'] == 3 ? "" : $anchorInfo['guild_num'],
                        'ctime' => time(),
                        'gold_from' => $goldFrom[$item['message_id']] ?? ''
                    ];

                    $messageIds[] = $item['message_id'];
                    $incomeArr[] = $income;

                } else {
                    if ($item['is_settle'] == 0 && $item['chat_type'] != 3) {
                        // 已过期消息，退回用户金币
                        $user_back = bcadd($user_back, $item['text_price'], 2);
                        $msgId[] = $item['message_id'];
                    }
                    $overMessageIds[] = $item['message_id'];
                }
            }

            $userModel->beginTA();

            try {
                if ($anchor_income > 0 && !empty($incomeArr)) {
                    // 更新用户积分
                    $userModel->updateUserIntegrateCount($anchor_id, $anchor_income);
                    // 插入用户收入记录
                    $userModel->insertAll($incomeArr, 'tb_income_expense');

                    // 更新用户亲密度
                    ClosenessModel::write($user_id, $anchor_id, $expend);

                    // 记录用户解锁微信进度
                    AnchorModel::recordWeixinProgress($user_id, $anchor_id, $expend);

                    // 增加男用户财富值，女用户魅力值
                    (new PayCallModel())->addUserWealth($user_id, $anchor_id, $expend);

                    // 修改消息记录为已结算
                    $changeWhere['message_id'] = ['$in' => $messageIds];
                    $set['$set'] = ['is_settle' => 1];
                    $res = $mongo->update($changeWhere, $set, MON_USER_CHAT, true, false);

                }
                if (!empty($messageIds) || !empty($overMessageIds)) {
                    // 给女用户发送im消息通知客户端
                    $msg = json_encode(array('event' => 'settle_msg', 'msg' => ['user_id' => $user_id, 'message_ids' => $messageIds, 'over_message' => $overMessageIds]));
                    (new WyyClient())->putAttachMsgQueue($user_id, intval($anchor_id), $msg);
                }

                if ($user_back > 0) {
                    // 更新用户金币
                    $userModel->updateUserGoldCount($user_id, $user_back);
                    // 插入用户金币退回记录
                    $backArr = [
                        'uid' => $user_id,
                        'user_id' => $anchor_id,
                        'type' => 1,
                        'sub_type' => 23,
                        'amount_type' => 1,
                        'amount' => $user_back,
                        'account' => bcadd($userInfo['gift_count'], $user_back, 2),
                        'ext' => json_encode(["p" => $anchorInfo['package'], 'v' => $anchorInfo['version_code'], 'c' => $anchorInfo['channel']]),
                        'rate' => 40,
                        'extend' => $msgId[0],
                        'from' => $userInfo['from'],
                        'version_code' => $userInfo['version_code'],
                        'channel' => $userInfo['channel'],
                        'package' => $userInfo['package'],
                        'guild_num' => '',
                        'ctime' => time(),
                    ];
                    $userModel->insert($backArr, 'tb_income_expense');
                }
                if (!empty($overMessageIds)) {
                    // 修改消息记录为已过期
                    $changeWhere['message_id'] = ['$in' => $overMessageIds];
                    $set['$set'] = ['is_settle' => 2];
                    $res = $mongo->update($changeWhere, $set, MON_USER_CHAT, true, false);

                    if (!empty($msgId)) {
                        if ($userInfo['online'] > 0) {
                            $msg = json_encode(['event' => 'overtime_msg', 'msg' => [['user_id' => $anchor_id, 'over_message' => $msgId]]]);
                            (new WyyClient())->putAttachMsgQueue($anchor_id, intval($user_id), $msg);
                        } else {
                            $insert = [
                                'to_uid' => $user_id,
                                'from_uid' => $anchor_id,
                                'message_ids' => implode(",", $msgId),
                                'ctime' => time(),
                                'is_send' => 0,
                                'send_time' => 0,
                            ];
                            $mongo->insert($insert, 'tb_message_expire');
                        }
                    }
                }

                $userModel->commit();
                return true;

            } catch (Throwable $e) {
                $userModel->rollBack();
                logInfo('message_settle', ['anchor_id' => $anchor_id, 'user_id' => $user_id, 'error' => [$e->getMessage(), $e->getFile(), $e->getLine()]]);
                return false;
            }
        }
        return false;
    }


    /**
     * 过期消息处理
     * @return void
     */
    public function messageExpire()
    {
        $mongo = new MonDB();
        $userModel = new UserModel();

        // 获取所有已过期的未处理消息
        $where = [
            'is_settle' => 0,
            'chat_type' => ['$in' => [4, 5]],
            'content_type' => ['$in' => [1, 2, 3]],
            'ctime' => ['$lte' => time() - 60],        // todo 测试过期时间为2分钟，正式上线为8小时
            'sex' => 1,
            'message_id' => ['$nin' => [null, '']]
        ];

        $options = array(
            'projection' => array('_id' => 0, 'uid' => 1, 'receive_uid' => 1, 'ctime' => 1, 'message_id' => 1, 'text_price' => 1, 'chat_type' => 1, 'content_type' => 1, 'is_settle' => 1),
            'skip' => 0,
            'sort' => array('ctime' => -1)
        );
        $result = $mongo->find($where, $options, MON_USER_CHAT);

        if (!empty($result)) {
            $backGold = [];
            $backArr = [];
            $messageIds = [];
            $overMessageIds = [];

            $uids = implode(",", array_unique(array_column($result, 'uid')));
            $receive_uids = implode(",", array_unique(array_column($result, 'receive_uid')));

            $users = $userModel->findAll('id,gift_count,package,version_code,channel,`from`,`online`', "id in ($uids)", [1]);
            $users = array_column($users, null, 'id');

            $anchors = $userModel->findAll('id,integrate_usable_count,version_code,`from`,package,version_code,channel,guild_num', "id in ($receive_uids)", [1]);
            $anchors = array_column($anchors, null, 'id');


            foreach ($result as $item) {
                $userInfo = $users[$item['uid']];
                $anchorInfo = $anchors[$item['receive_uid']];

                $overMessageIds[] = $item['message_id'];
                $messageIds[$item['uid']][$item['receive_uid']][] = $item['message_id'];

                $backGold[$item['uid']][$item['receive_uid']] = bcadd($backGold[$item['uid']][$item['receive_uid']] ?? 0, $item['text_price'], 2);

                $backArr[$item['uid']][$item['receive_uid']] = [
                    'uid' => $item['uid'],
                    'user_id' => $item['receive_uid'],
                    'type' => 1,
                    'sub_type' => 23,
                    'amount_type' => 1,
                    'amount' => 0,
                    'account' => 0,
                    'ext' => json_encode(["p" => $anchorInfo['package'], 'v' => $anchorInfo['version_code'], 'c' => $anchorInfo['channel']]),
                    'rate' => 40,
                    'extend' => $messageIds[$item['uid']][$item['receive_uid']][0],
                    'from' => $userInfo['from'],
                    'version_code' => $userInfo['version_code'],
                    'channel' => $userInfo['channel'],
                    'package' => $userInfo['package'],
                    'guild_num' => '',
                    'ctime' => time(),
                ];

            }

            foreach ($users as $uid => $user) {
                $gold = 0;
                $msgs = [];
                foreach ($anchors as $aid => $anchor) {
                    if (isset($backArr[$uid][$aid])) {
                        $gold += $backGold[$uid][$aid];
                        $backArr[$uid][$aid]['amount'] = $backGold[$uid][$aid];
                        $backArr[$uid][$aid]['account'] = $user['gift_count'] + $gold;

                        $msgs[] = ['user_id' => $aid, 'over_message' => $messageIds[$uid][$aid]];

                        if ($user['online'] == 0) {
                            $insert = [
                                'to_uid' => $uid,
                                'from_uid' => $aid,
                                'message_ids' => implode(",", $messageIds[$uid][$aid]),
                                'ctime' => time(),
                                'is_send' => 0,
                                'send_time' => 0,
                            ];
                            $mongo->insert($insert, 'tb_message_expire');
                        }

                    }
                }


                // 更新用户金币
                $userModel->updateUserGoldCount($uid, $gold);
                // 插入用户金币退回记录
                $income = array_values($backArr[$uid]);
                $userModel->insertAll($income, 'tb_income_expense');

                if ($user['online'] > 0) {
                    $msg = json_encode(['event' => 'overtime_msg', 'msg' => $msgs]);
                    (new WyyClient())->putAttachMsgQueue($aid, intval($uid), $msg);
                }
            }


            // 修改消息记录为已已处理
            $changeWhere['message_id'] = ['$in' => $overMessageIds];
            $set['$set'] = ['is_settle' => 3];
            $res = $mongo->update($changeWhere, $set, MON_USER_CHAT, true, false);

        } else {
            echo '无数据';
        }
    }


    /**
     * 用户上线后发送已过期消息提示
     * @param $uid
     * @return true
     */
    public function sendExpireMsg($uid)
    {
        $mongo = new MonDB();
        // 获取所有已过期的未处理消息
        $where = [
            'is_send' => 0,
            'to_uid' => intval($uid),
        ];
        $options = array(
            'projection' => array('_id' => 0),
            'skip' => 0,
            'sort' => array('ctime' => -1)
        );
        $result = $mongo->find($where, $options, 'tb_message_expire');

        if (!empty($result)) {
            $msgs = [];
            $from_uid = 0;
            foreach ($result as $item) {
                $msgs[] = ['user_id' => $item['from_uid'], 'over_message' => explode(',', $item['message_ids'])];
                $from_uid = $item['from_uid'];
            }

            $msg = json_encode(['event' => 'overtime_msg', 'msg' => $msgs]);
            (new WyyClient())->putAttachMsgQueue($from_uid, intval($uid), $msg);

            // 修改消息为已发送
            $changeWhere['is_send'] = 0;
            $changeWhere['to_uid'] = intval($uid);
            $set['$set'] = ['is_send' => 1, 'send_time' => time()];
            $res = $mongo->update($changeWhere, $set, 'tb_message_expire', true, false);
        }
        return true;
    }


    /**
     * Note - 判断用户上一条消息是否为红线消息
     * DateTime 2024/8/12 19:09
     * User Admin
     * @param $uid
     * @param $toUid
     * @return int
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getReadMsg($uid, $toUid)
    {
        $mongo = MongoDBClient::getInstance();
        $time = strtotime(date('Y-m-d'));
        $where = [
            '$or' => [
                ['uid' => $uid, 'receive_uid' => $toUid],
                ['uid' => $toUid, 'receive_uid' => $uid]
            ],
            'ctime' => ['$gte' => $time]
        ];
        $options = [
            'projection' => ['_id' => 0, 'uid' => 1, 'receive_uid' => 1, 'content' => 1, 'ctime' => 1, 'message_id' => 1, 'text_price' => 1, 'chat_type' => 1, 'content_type' => 1, 'is_settle' => 1],
            'limit' => 1,
            'skip' => 0,
            'sort' => ['ctime' => -1]
        ];
        $result = $mongo->find('tb_user_chat_v2', $where, $options);
        if (!empty($result) && isset($result[0]['chat_type']) && $result[0]['chat_type'] == 3) {
            return 1;
        }
        return 0;
    }


    public function getContactFlag($userInfo, $tarUserInfo, $option)
    {
        $rs = 0;
        $flag = false;
        if ($_REQUEST['from'] == 1 && $_REQUEST['version_code'] > 120) {
            $flag = true;
        }
        if (($_REQUEST['from'] == 2) && $_REQUEST['version_code'] > 4) {
            $flag = true;
        }
        /*if($_REQUEST['channel']=='test001'){
            $flag=true;
        }*/
        if ($flag /*&& $tarUserInfo['vip']==0*/) {
            $rate = (int)$this->_commonConfig['contact_msg_rate'];
            if ($rate > 0 && $rate <= 100) {
                $num = mt_rand(0, 100);
                if ($num <= $rate) {
                    $rs = 1;
                }
            }
        }

        return $rs;
    }

    //////////////////////////////2016-10-13-增加套路消息-start///////////////////////////////////////

    /**
     * 获取使用套路消息还是非套路消息
     * @return int
     */
    public function getIsGroupMsg($userInfo, $option)
    {
        $status = 0;
        $channel = $_REQUEST['channel'];
        if ($option['gid'] > 0 && $option['user_id'] > 0) {
            $status = 1;
        }
        if ($option['stage_type'] == 8) {
            return 0;
        }
        if ($option['user_id'] == -1 && $option['msg_type'] == 1 && $userInfo['sex'] == 1 && $option['stage_type'] != 6) {
            $flag = false;
            if ($_REQUEST['from'] == 1 && $_REQUEST['version_code'] > 15) {
                $flag = true;
            }
            if ($_REQUEST['from'] == 2 && $channel != "ipstore" && $_REQUEST['version_code'] > 6) {
                $flag = true;
            }
            if ($flag) {
                $diff = $this->diff_group_msg($userInfo, $option);
                $rate = intval($this->_commonConfig['group_rate']);
                if (!empty($diff)) {
                    $num = mt_rand(0, 100);
                    if ($num < $rate) {
                        $status = 1;
                    }
                }
            }
        }
        if (in_array($_REQUEST['channel'], array('p100007'))) {
            $status = 0;
        }
        return $status;
    }

    public function getGroupMessageData($userInfo, $option)
    {

        $next_step = 0;
        $msg = array();
        $groupData = $this->getGroupMsgByDb();
        if ($option['g_type'] > 0 && $option['user_id'] > 0) {
            //已确定套路id和机器人id
            $data = $groupData[$option['user_id']];
            $msg = (array)$data[$option['g_type']];
            $next_step = 0;

            if (!empty($data)) {
                $all_keys = array_keys($data);
                foreach ($all_keys as $k => $v) {
                    if ($v == $option['g_type']) {
                        $next_step = (int)$all_keys[$k + 1];
                        break;
                    }
                }
            }

        } elseif ($option['user_id'] == -1) {
            //获取套路id
            $groupData = $this->diff_group_msg($userInfo, $option);
            $all_keys = array_keys($groupData);
            $fristIndex = (int)$all_keys[0];
            $tag_uid = $fristIndex;
            $tag_uid = array_rand($groupData);  //随机出现套路消息

            $g_msg = $groupData[$tag_uid];
            if (!empty($g_msg)) {
                reset($g_msg);
                $msg = current($g_msg);   //获取第一条
                next($g_msg);
                $next_arr = current($g_msg);
                $next_step = (int)$next_arr['step'];
            }
        }
        if (!empty($msg)) {
            $msg['next_step'] = $next_step;
        }

        return $msg;
    }

    /**
     * 数据库获取所有套路消息
     * @return array
     */
    public function getGroupMsgByDb()
    {
        $flag = false;
        $indexCount = Mem::get('api_group_message_db_new_index_count');
        if ($indexCount === false) {
            $flag = true;
        } else {
            for ($i = 0, $len = intval($indexCount); $i < $len; $i++) {
                $item = Mem::get("api_group_message_db_new_" . $i);
                if ($item === false) {
                    $flag = true;
                    break;
                } else {
                    $sonData1[$i] = $item;
                }
            }

        }

        if ($flag) {
            $page = 3;
            $robotModel = new RobotmessageModel();
            $data = $robotModel->getRobotSeriesMsg();

            if (!empty($data)) {
                foreach ($data as $k => $v) {
                    $mi = $k % $page;
                    $sonData[$mi][$k] = $v;
                }
            }

            if (!empty($sonData)) {
                foreach ($sonData as $item => $value) {
                    Mem::set("api_group_message_db_new_" . $item, $value, 300);
                }
                Mem::set("api_group_message_db_new_index_count", count($sonData), 300);     //所有消息分拆的个数
            }
        } else {

            $data = array();
            if (!empty($sonData1)) {
                foreach ($sonData1 as $v1) {
                    foreach ($v1 as $k2 => $v2) {
                        $data[$k2] = $v2;
                    }
                }
            }
            ksort($data);
        }

        $msg = array();
        $filterUids = $this->getFilterGroupUids();
        if (!empty($data)) {
            foreach ($data as $v) {
                if (!in_array($v['uid'], $filterUids)) {
                    $msg[$v['uid']][$v['step']] = $v;
                }

            }
        }

        return $msg;
    }

    public function diff_group_msg($userInfo, $option)
    {
        $groupData = $this->getGroupMsgByDb();
        $historyGids = $option['gids'];
        $historyGidsArrV2 = array();
        if (!empty($historyGids)) {
            $historyGids = trim($historyGids, ",");
            $historyGidsArr = explode(',', $historyGids);
            if (!empty($historyGidsArr)) {
                foreach ($historyGidsArr as $v2) {
                    $historyGidsArrV2[$v2] = $v2;
                }
            }
        }
        $groupDataV2 = array();
        foreach ($groupData as $k1 => $v1) {
            reset($v1);
            $tmp = current($v1);
            $groupDataV2[$tmp['series_id']] = $v1;
            unset($tmp);
        }
        $diff = (array)array_diff_key($groupDataV2, $historyGidsArrV2);
        $msg = array();
        if (!empty($diff)) {
            foreach ($diff as $k3 => $v3) {
                reset($v3);
                $tmp = current($v3);
                $msg[$tmp['uid']] = $v3;
                unset($tmp);
            }
        }
        return $msg;
    }

    public function filterUids()
    {
        $uids = Mem::get("all_group_uids");
        if ($uids === false) {
            $uids = array();
            $model = new Model();
            $allInfo = $model->findAll("id,uid", "1", array(1), '', '', 'tb_robot_series');
            if (!empty($allInfo)) {
                foreach ($allInfo as $v) {
                    $uids[$v['id']] = $v['uid'];
                }
            }
            Mem::set("all_group_uids", $uids, 3600);
        }

        return $uids;
    }

    //禁言的套路机器人用户id
    public function getFilterGroupUids()
    {
        return array('10010465', '10010153', '10010091', '10175538');
    }

    //////////////////////////////2016-10-13-增加套路消息-end///////////////////////////////////////
    public function dealPayGuide($data)
    {
        if ($_REQUEST['from'] == 1) {
            if (!empty($data)) {
                if ($data['type'] == 6) {
                    $allGroupUids = $this->filterUids();
                    if (in_array($data['user_info']['id'], $allGroupUids)) {
                        //是套路机器人
                        $gid = (int)array_search($data['user_info']['id'], $allGroupUids);
                        $data['gid'] = $gid;
                        $data['g_type'] = 0;
                        $data['g_interval'] = 0;
                    }
                }
            }
        }
        return $data;
    }

    //2016-10-13-增加非vip引导判断
    public function checkNovipGuide($userInfo)
    {
        //echo '123';
        $cfg = array(
            1 => array('playTime' => 1000, 'orderNum' => 30, 'msgNum' => 120),//正式350
            2 => array('playTime' => 1000, 'orderNum' => 20, 'msgNum' => 120)//正式300
        );
        $_cfg = $cfg[intval($_REQUEST['from'])];

        $chatNum = Mem::get('novip_guide_user_chatNum_' . $userInfo['id']);
        if ($chatNum === false) {
            $mongo = new MonDB();
            $mongo->selectCollection(MON_USER_CHAT);
            $query['aggregate'] = MON_USER_CHAT;
            $query['pipeline'] = array(
                array(
                    '$match' => array('ctime' => array('$gte' => time() - 86400, '$lte' => time()), 'receive_uid' => (int)$userInfo['id'], 'chat_type' => 3),
                ),
                array(
                    '$group' => array('_id' => null, 'sum' => array('$sum' => 1)),
                ),
            );
            $result = $mongo->query($query);
            //var_dump($result);
            @$chatNum = intval($result[0]->result[0]->sum);
            //var_dump($chatNum);
            /*$chat = $model->find('count(*) as num','receive_uid = ? and chat_type = ?',array($userInfo['id'],3),'','tb_user_chat');
            $chatNum = (int)$chat['num'];*/
            Mem::set('novip_guide_user_chatNum_' . $userInfo['id'], $chatNum, 300);
        }

        if ($chatNum >= $_cfg['msgNum']) {
            return true;    //未付费引导
        }

        return false;
    }

    //非vip引导
    public function getNovipSpreadApp()
    {
        return array(
            'app_name' => '95约吧',
            'app_url' => IMAGE_HOST . 'html/spread/live_1.html?test998',
            'ios_url' => IMAGE_HOST . 'html/spread/live_1.html?test998',
        );
    }

    /**
     * 用户接受不到消息
     * @return int
     */
    public function checkUserChat()
    {
        $ret = 0; //0能接收，1不能接收

        if (in_array($_REQUEST['uid'], array('12529118')) || in_array($_REQUEST['imei'], array('1ADDA8DC-6AAB-4D0A-B2DC-AA0A9428E055'))) {
            $ret = 1;
        }

        if ($_REQUEST['from'] == 2 && $_REQUEST['package'] == 'com.LokeSeekL.www') {
            $ret = 1;
        }
        if (Fun::apkcheckChannel()) { //审核包
            $ret = 1;
        }
        if (in_array(Fun::getClientIp(), array('121.32.35.189'))) {
            $ret = 1;
        }
        if (in_array($_REQUEST['channel'], array('x710050', 'u200116', 'l200001', 'l200002', 'test001'))) {
            // $ret=1;
        }
        if (substr($_REQUEST['channel'], 0, 5) == 'jginb') {
            //女版不能接受消息
            $ret = 1;
        }
        if (in_array($_REQUEST['channel'], array('market2_9.28', 'market1_9.28', 'bdmarket9.25'))) {
            $ret = 1;
        }
        if ($_REQUEST['from'] == 2 && !in_array($_REQUEST['package'], array('com.lele.live', 'com.loke.citylovelove', 'com.lokeyajy.www', 'com.lokexiaojinfive.cityAppointments', 'com.jysy.www', 'com.LokeSeekL.www', 'com.tongchenglianyuan.www', 'com.lokexyw.www', 'com.lokeylsy.www', 'com.xunai.aiphon7', 'com.tongcheng.aiphon6', 'com.luoke.onecitylove', 'com.xtj.starland', 'com.midnightlover.www', 'com.tongcheng.aiphonEight', 'com.yllr.www', 'com.dsyh.com', 'com.tongcheng.aiphonseven', 'com.xtjy.yiyang', 'com.yuehuiba.www', 'com.knhsjuys.tongcheng', 'com.fjyhb.project1', 'com.jiansi.tongchengyuehuijiaoyou', 'com.tcmyh.project1', 'com.tcyyh.k', 'com.Jwhgui.Duhwq', 'com.tcyhjy.project1', 'com.atmanas.wyyouyue', 'com.bobojiaoyou.bbjy2', 'com.tongchengxiangyuea.appname', 'com.ygbh.www', 'com.jimojiaoyou.www', 'com.yaoyueai.www', 'com.tcyyh.k', 'com.tongchengxiangyuea.appname', 'com.tcyyyh.www', 'com.wyjy.www', 'com.papajy.www', 'com.jiaoyoume.www', 'jiaoyouba.ios', 'com.tcmy1.www', 'com.mitao.mitaoyueai', 'com.yuehuiba.name', 'com.starry.huanle', 'com.tvyl.name', 'com.yajy.name', 'com.tongcheng.aiphonNine', 'com.tcyh.name', 'com.tcyp.name', 'com.tongcheng.aiphonTen', 'com.meihuyue.name', 'com.tongchengmiyou1.name', 'com.jy.phonEleven', 'com.xyxy.Eighteen'))) {
            $ret = 1;
        }
        /*$url="http://api.map.baidu.com/location/ip?ak=avG2C8Mqh6RqB7SVpx1KgNqLG1NEsxyf&coor=bd09ll&ip=".Fun::getClientIp();
        $place = json_decode(file_get_contents($url),true);
        $add=$place['content']['address_detail']['city'];
        if($add=='西安市'){
            $ret=1;
        }*/

        return $ret;
    }

    //伪索礼：带礼物图的索礼
    public function getForgedExtraData($m_id, $content)
    {
        $giftModel = new GiftModel();
        $gift_list = $giftModel->getAllGift(); //礼物以按价格升序排列
        if (empty($gift_list)) {
            return array();
        }
        $gift_list = array_slice($gift_list, 0, 4);
        switch ($m_id) {
            case '1946':
                $gift = $gift_list[0];
                $arr = array(
                    "content" => "哥哥在吗，可以送我" . $gift['name'] . "吗？",
                    "g_num" => 1
                );
                break;
            case '1947':
                $gift = $gift_list[1];
                $arr = array(
                    "content" => "你好，在吗？可以送我礼物么？",
                    "g_num" => 1
                );
                break;
            case '1948':
                $gift = $gift_list[2];
                $arr = array(
                    "content" => "帅哥，求个礼物打赏下呗",
                    "g_num" => 1
                );
                break;
            case '1949':
                $gift = $gift_list[3];
                $arr = array(
                    "content" => "哥 好像这个软件可以送礼 可以送我一份么",
                    "g_num" => 1
                );
                break;
            /*此段为了兼容测试服>>*/
            case '1010':
            case '1011':
            case '1012':
            case '1013':
            case '1014':
            case '1015':
                $gift = $gift_list[mt_rand(0, 3)];
                $arr = array(
                    "content" => $content,
                    "g_num" => 1
                );
                break;
            /*<<此段为了兼容测试服*/
            default:
                return array();
                break;
        }
        $arr['gid'] = $gift['id'];
        $arr['g_img'] = $gift['img'];
        $arr['g_price'] = $gift['price'];
        $arr['g_name'] = $gift['name'];

        return $arr;
    }

    //2017-12-7新增“发信息消耗邮票”的功能
    public function payForMessageWithStamp($uid, $cost_stamp)
    {
        if ($cost_stamp <= 0) {
            return array('code' => 0, 'msg' => '不消耗邮票');
        }

        $userModel = new UserModel();
        $userModel->setActive();
        $userModel->beginTA();

        $userModel->reduceUserStamp($uid, $cost_stamp);
        $ret = $userModel->find('chat_key', 'id = ?', array($uid));
        if ($ret['chat_key'] < 0) {
            $userModel->rollBack();
            return array('code' => -1, 'msg' => '用户邮票不足');
        }

        $insertData = array(
            'uid' => $uid,
            'type' => 2,
            'amount' => $cost_stamp,
            'stamp_account' => $ret['chat_key'],
            'ctime' => time(),
            'from' => intval($_REQUEST['from']),
            'version_code' => intval($_REQUEST['version_code']),
            'channel' => trim($_REQUEST['channel']),
            'ip' => trim(Fun::getClientIp()),
        );
        $insertId = $userModel->insert($insertData, 'tb_stamp_record');
        if (!$insertId) {
            $userModel->rollBack();
            return array('code' => -2, 'msg' => '生成消费记录失败');
        }
        $userModel->commit();

        Mem::delete("userInfo_" . $uid);
        $userInfo = $userModel->findUserInfoById($uid);

        return array('code' => 1, 'userInfo' => $userInfo);

    }

    /**
     * 获取聊天会话
     *
     * @param int $uid 用户id(男)
     * @param int $anchor_id 主播id(女)
     * @param int $type 是否用户获取聊天会话 0否 1是
     * @return array
     */
    public function getChatSession($uid, $anchor_id, $type = 0)
    {
        $model = new Model();
        $chat_session = $model->find('*', 'user_id = ? and anchor_id = ?', [$uid, $anchor_id], '', 'tb_chat_session');

        if (empty($chat_session)) {
            $model->insert([
                'user_id' => $uid,
                'anchor_id' => $anchor_id,
            ], 'tb_chat_session');
            $chat_session = $model->find('*', 'user_id = ? and anchor_id = ?', [$uid, $anchor_id], '', 'tb_chat_session');
        }

        // 判断聊天主播是否开启托管功能的判断
        // if ($chat_session['chat_hosting_anchor_id'] > 0) {
        //     $anchor = $model->find('uid, auto_reply_status', 'uid = ?', [$anchor_id], '', 'tb_anchor');
        //     if ($anchor['auto_reply_status'] == 0) {
        //         $this->endChatHosting($chat_session);
        //         $chat_session['chat_hosting_anchor_id'] = 0;
        //     }
        // }

        // 判断主播是否在线, 不在线就重新分配给在线的聊天主播 // 消息数重新清零
        if ($type == 1 && $chat_session['chat_hosting_anchor_id'] > 0) {
            $chat_hosting_config = include ROOT_PATH . "/configs/chat_hosting.config.php";
            $chat_hosting_anchor_id = $chat_hosting_config['chat_hosting_anchor_id'];
            $chat_hosting_anchor_id_str = empty($chat_hosting_anchor_id) ? '-1' : implode(',', $chat_hosting_anchor_id);
            // 获取当前登录聊天主播包的聊天主播
            $chat_hosting_anchor = $model->findAll('id', "json_extract(ext2, '$.version_code') = ? and id in ({$chat_hosting_anchor_id_str})", ['500'], '', '', 'tb_user');
            $chat_hosting_anchor_ids = array_column($chat_hosting_anchor, 'id');

            $online_uids = (new UserModel())->getOnlineUids(2);
            // 当前登录聊天主播包的在线聊天主播
            $online_chat_hosting_anchor_ids = array_intersect($online_uids, $chat_hosting_anchor_ids);

            // 当前分配的聊天主播不在 $online_chat_hosting_anchor_ids 中
            if (!in_array($chat_session['chat_hosting_anchor_id'], $online_chat_hosting_anchor_ids)) {
                if (!empty($online_chat_hosting_anchor_ids)) {
                    $hosting_anchor_id = $online_chat_hosting_anchor_ids[array_rand($online_chat_hosting_anchor_ids)];
                    $model->update($chat_session['id'], ['chat_hosting_anchor_id' => $hosting_anchor_id, 'hosting_anchor_unread' => 0, 'last_hosting_anchor_id' => $chat_session['chat_hosting_anchor_id']], 'tb_chat_session');
                    $chat_session['chat_hosting_anchor_id'] = $hosting_anchor_id;
                } else {
                    // 没有可分配的聊天主播
                    $model->update($chat_session['id'], ['chat_hosting_anchor_id' => 0, 'hosting_anchor_unread' => 0, 'last_hosting_anchor_id' => $chat_session['chat_hosting_anchor_id']], 'tb_chat_session');
                    $chat_session['chat_hosting_anchor_id'] = 0;
                }
            }
        }

        return $chat_session;
    }

    /**
     * 结束聊天托管
     *
     * @param array $chat_session 聊天会话记录
     */
    public function endChatHosting($chat_session)
    {
        // 清除该会话已分配的聊天主播id
        (new Model())->update($chat_session['id'], ['chat_hosting_anchor_id' => 0, 'hosting_anchor_unread' => 0, 'last_hosting_anchor_id' => $chat_session['chat_hosting_anchor_id']], 'tb_chat_session');

        // 推送结束托管聊天socket消息给该会话已分配的聊天主播
        Fun::socket_client('chat_hosting', $chat_session['chat_hosting_anchor_id'], 111, ['uid' => $chat_session['user_id'], 'anchor_id' => $chat_session['anchor_id'], 'type' => 2]); // type 1:开始托管聊天 2:结束托管聊天
    }

    /**
     * 聊天主播统计消息数据
     *
     * @param array $chat_session 会话记录
     * @param int $type 类型 1:用户发送消息 2:聊天主播发送消息
     */
    public function statisticsChatHosting($chat_session, $type)
    {
        $day_time = strtotime(date("Y-m-d"), time());
        if ($type == 1) {
            $sql = "insert into tb_chat_hosting_statistics (chat_hosting_anchor_id, anchor_id, user_id, day_time, user_news) values(?, ?, ?, ?, ?) on DUPLICATE key update user_news = user_news + 1";
        } else {
            $sql = "insert into tb_chat_hosting_statistics (chat_hosting_anchor_id, anchor_id, user_id, day_time, anchor_news) values(?, ?, ?, ?, ?) on DUPLICATE key update anchor_news = anchor_news + 1";
        }
        (new Model())->execute($sql, [$chat_session['chat_hosting_anchor_id'], $chat_session['anchor_id'], $chat_session['user_id'], $day_time, 1]);
    }

    /**
     * 检查私信是否需要收费
     * @param $uid
     * @param $receive_uid
     * @return bool
     */
    public function checkNewUserWelfare($uid, $receive_uid, $chat_type = 4)
    {
        $chat_num = $this->getSenderNumByReceiveUid($uid, $receive_uid, $chat_type);

        if ($chat_num >= 3) {
            return 0;
        } else {
            $send_user_num = $this->getSenderUserNum($uid, $chat_type);
            $send_uid_list = $this->getSenderUids($uid, $chat_type);

            if ($send_user_num >= 5 && !in_array($receive_uid, $send_uid_list)) {
                //修改用户属性
                $userModel = M('user');
                $data['is_newuser_welfare'] = 0;
                $userModel->updateByWhere($data, "id = {$uid}");

                return 0;
            }
        }
        return 1;
    }

    public function getSenderNumByReceiveUid($uid, $receive_uid, $chat_type = 4)
    {
        if (is_array($chat_type)) {
            $chat_type = ['$in' => $chat_type];
        }

        $mongo = new MonDB();
        $mongo->selectCollection(MON_USER_CHAT);
        $query['aggregate'] = MON_USER_CHAT;
        $query['pipeline'] = array(
            array(
                '$match' => array('uid' => (int)$uid, 'receive_uid' => (int)$receive_uid, 'chat_type' => $chat_type),
            ),
            array(
                '$group' => array('_id' => null, 'sum' => array('$sum' => 1)),
            ),
        );
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);

        $num = intval($result[0]->sum);
        return intval($num);
    }

    public function getSenderNum($uid)
    {
        $mongo = new MonDB();
        $query['aggregate'] = MON_USER_CHAT;
        $query['pipeline'] = array(
            array(
                '$match' => array('uid' => (int)$uid, 'chat_type' => 4),
            ),
            array(
                '$group' => array('_id' => 'receive_uid', 'sum' => array('$sum' => 1)),
            ),
        );
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);
        $num = intval($result[0]->sum);
        return intval($num);
    }

    public function getSenderUserNum($uid, $chat_type = 4)
    {
        if (is_array($chat_type)) {
            $chat_type = ['$in' => $chat_type];
        }
        $mongo = new MonDB();
        $query['aggregate'] = MON_USER_CHAT;
        $query['pipeline'] = array(
            array(
                '$match' => array('uid' => (int)$uid, 'chat_type' => $chat_type),
            ),
            array(
                '$group' => array('_id' => '$receive_uid', 'sum' => array('$sum' => 1)),
            ),
        );
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);
        return sizeof($result);
    }

    public function getSenderUids($uid, $chat_type = 4)
    {
        if (is_array($chat_type)) {
            $chat_type = ['$in' => $chat_type];
        }
        $mongo = new MonDB();
        $query['aggregate'] = MON_USER_CHAT;
        $query['pipeline'] = array(
            array(
                '$match' => array('uid' => (int)$uid, 'chat_type' => $chat_type),
            ),
            array(
                '$group' => array('_id' => '$receive_uid'),
            ),
        );
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);
        return array_column($result, "_id");
    }

    public function getSenderGuildNum($guild_num)
    {
        $mongo = new MonDB();
        $query['aggregate'] = MON_USER_CHAT;
        $query['pipeline'] = array(
            array(
                '$match' => array('guild_num' => $guild_num, 'chat_type' => 4, 'content_type' => ['$in' => [1, 2, 3]]),
            ),
            array(
                '$group' => array('_id' => '$guild_num', 'sum' => array('$sum' => 1)),
            ),
        );
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);
        $num = intval($result[0]->sum);
        return $num;
    }

    public function getTodaySenderUserNum($uid)
    {
        $time = strtotime('midnight');
        $mongo = MongoDBClient::getInstance();
        $query['aggregate'] = 'tb_user_chat_v2';
        $query['pipeline'] = array(
            array(
                '$match' => array('uid' => $uid, 'chat_type' => 4, 'ctime' => array('$gte' => $time)),
            ),
            array(
                '$group' => array('_id' => '$receive_uid', 'sum' => array('$sum' => 1)),
            ),
        );
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);
        return sizeof($result);
    }

    /**
     * 查询判断主播消息 设置主播排序
     * @param $userInfo
     * @param $user_id
     * @return int
     */
    public function findAnchorForSort($userInfo, $user_id)
    {
        try {
            $anchor_id = intval($userInfo['id']);
            $mongo = new MonDB();
            $where['$or'] = [
                array('uid' => $user_id, 'receive_uid' => $anchor_id, 'chat_type' => 4, 'content_type' => ['$in' => [1, 2, 3]]),
                array('uid' => $anchor_id, 'receive_uid' => $user_id, 'chat_type' => 4, 'content_type' => ['$in' => [1, 2, 3]])
            ];

            $options = array(
                'projection' => array('_id' => 0),
                'skip' => 0,
                'limit' => 5,
                'sort' => array('ctime' => -1)
            );

            $result = $mongo->find($where, $options, MON_USER_CHAT);
            if (empty($result)) {
                // 没有消息 主动私信 记录主播排序分
                AnchorSortLogModel::record($anchor_id, 9, 1);
            } else {
                $msg = $result[0];
                if ($userInfo['online'] == 1 && $msg['receive_uid'] == $anchor_id) {
                    $ctime = $msg['ctime'];
                    $time = time() - $ctime;

                    if ($time > 185) {
                        // 无效回复私信 记录主播排序分
                        AnchorSortLogModel::record($anchor_id, 17, 1);
                    } else {
                        // 有效回复私信 记录主播排序分
                        AnchorSortLogModel::record($anchor_id, 10, 1);
                    }
                }
            }
            return true;
        } catch (Throwable $e) {
        }
    }


    /**
     * 用户之间是否有过聊天或者视频通话过
     * @param $user_id
     * @param $anchor_id
     * @return int 1用户未回复 2无交流
     */
    public function checkChatExchange($user_id, $anchor_id)
    {
        $call_id = (new PayCallModel())->find('id', 'user_id=? and anchor_id=? and start_time>0 and end_time>0', [$user_id, $anchor_id]);
        if (!empty($call_id)) {
            return 0;
        }

        $mongo = new MonDB();
        // 主播发送的私信
        $where['$or'] = [
            array('uid' => $anchor_id, 'receive_uid' => $user_id, 'chat_type' => 4, 'content_type' => ['$in' => [1, 2, 3]])
        ];

        $options = array(
            'projection' => array('_id' => 0),
            'skip' => 0,
            'limit' => 5,
            'sort' => array('ctime' => -1)
        );
        $result = $mongo->find($where, $options, MON_USER_CHAT);

        if (empty($result)) {
            return 2;
        }

        // 用户发送的私信
        $where = [];
        $where['$or'] = [
            array('uid' => $user_id, 'receive_uid' => $anchor_id, 'chat_type' => 4, 'content_type' => ['$in' => [1, 2, 3]]),
        ];
        $result2 = $mongo->find($where, $options, MON_USER_CHAT);

        if (empty($result2)) {
            return 1;
        }
        return 0;
    }


    /**
     * 获取前1分钟内接收过分发、搭讪新用户消息大于等于2的男用户id
     * @return array
     */
    public function getReceiveId($time)
    {

        $num = 2;
        // if(substr(time(),-1) > 6){
        // 	$num = 3;
        // }

        $mongo = new MonDB();
        $query['aggregate'] = MON_USER_CHAT;
        $query['pipeline'] = [
            [
                '$match' => ['ctime' => array('$gte' => time() - $time), 'receive_sex' => 1, 'chat_type' => ['$in' => [3, 5]]],
            ],
            [
                '$group' => ['_id' => '$receive_uid', 'first' => ['$first' => '$receive_sex'], 'sum' => array('$sum' => 1)],
            ],
            ['$match' => ['sum' => ['$gte' => $num]]],
            ['$limit' => 500],
        ];
        $query['cursor'] = ['batchSize' => 0];
        $result = $mongo->query($query);
        // var_dump($result);exit;
        // echo json_encode($result);exit;
        $data = [];
        foreach ($result as $v) {
            $data[] = $v->_id;
        }
        return $data;
    }
}